package cn.corffen.test.algorithm.design;

import cn.corffen.test.algorithm.leetcode.TreeNode;

import java.util.ArrayList;

public class SerializeTree {

    private String s;

    String Serialize(TreeNode root) {
        if (root == null) {
            return "#";
        }
        return root.val + " " + Serialize(root.left) + " " + Serialize(root.right);
    }

    TreeNode Deserialize(String str) {
        this.s = str;
        return deserial();
    }

    TreeNode deserial() {
        if (s.length() == 0) {
            return null;
        }
        int index = s.indexOf(" ");
        String node = index == -1 ? s : s.substring(0, index);
        s = index == -1 ? "" : s.substring(index + 1);
        if (node.equals("#")) {
            return null;
        }
        int val = Integer.valueOf(node);
        TreeNode t = new TreeNode(val);
        t.left = deserial();
        t.right = deserial();
        return t;
    }


}
